package com.example.demo.utils;

import java.util.ArrayList;
import java.util.List;

public class Desk {
    private List<String> list = new ArrayList<String>();

    //放包子
    public synchronized void put() {
        try {
            String name = Thread.currentThread().getName();
            if (list.isEmpty()) {
                list.add(name + "做的包子");
                System.out.println(name + "做了一个包子");
                Thread.sleep(2000);
                //唤醒别人,等待自己
                this.notifyAll();
                this.wait();
            } else {
                //有包子就不做了
                //唤醒别人,等待自己
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    //吃包子
    public synchronized void eat() {
        try {
            String name = Thread.currentThread().getName();
            if (list.size() == 1) {
                System.out.println(name + "吃了：" + list.get(0));
                list.clear();
                Thread.sleep(1000);
                this.notifyAll();
                this.wait();
            } else {
                //没有包子
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

    }
}
